<template>
    <el-upload ref='uploadRef' v-model:file-list="fileList" drag :action="filesUploadUrl" :data="{ pid: dirId }"
        :auto-upload='true' :show-file-list="false" accept="image/*,video/*" :headers='headers' list-type="picture"
        :http-request="httpRequest" multiple>
        <el-icon class="el-icon--upload">
            <upload-filled />
        </el-icon>
        <div class="el-upload__text">
            拖动图片上传 或<em>点击上传</em>
        </div>
    </el-upload>
    <div style="padding: 5px;">
        <el-row :gutter='10'>
            <el-col :span="24">
                <div v-for="item of upuloadFiles" style="padding:3px">
                    <el-progress :text-inside="true" :stroke-width="25" :percentage="item.progress" status="success">
                        <span>{{ item.fileName }}</span>
                    </el-progress>
                </div>
            </el-col>

            <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for='item of files[dirId]'>
                <div class="square">
                    <div class="content">
                        <label :for="'subscribefiles' + item.id" class="file-checkbox">
                            <div :style="{ 'background-color': selectedOptionsObj[item.id] ? '#67C23A' : '#CDD0D6' }">
                                <el-icon v-show="selectedOptionsObj[item.id]"><Select /></el-icon>
                                <el-icon v-show="!selectedOptionsObj[item.id]">
                                    <Close />
                                </el-icon>
                            </div>
                        </label>
                        <input type="checkbox" v-model="selectedOptions" :value="item.id" :id="'subscribefiles' + item.id"
                            style="display:none"> </input>
                        <FileItem :item="item" @picture-card-preview="handlePictureCardPreview" />
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
    <el-dialog v-model="dialogVisible" fullscreen align-center style="text-align:center;"
        @click="$event => dialogVisible = !dialogVisible">
        <el-image style="width: 80vm; height:80vh;" :src="dialogImageUrl" fit="contain" />
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { storeToRefs } from 'pinia'
import FileItem from './file-item.vue'
import http from '@/utils/axios.js'
import { createThumbnail, createImageUrl } from '@/utils/image.js'
import { compressImage } from '@/utils/compressor.js'
import { fileQueueHandle } from '@/utils/file-queue.js'
import FilesStore from '@/stores/files.js'
import UserStores from '@/stores/user.js'
import {  ElNotification } from 'element-plus'

const { files, addFiles, addFile } = FilesStore()
const userStore = UserStores()
const authorization = computed(() => userStore.token)
const props = defineProps({
    dirId: {
        type: Number,
        default: 0
    }
})
const dirId = computed(() => props.dirId)
const upuloadFiles = computed(() => fileQueueHandle.completion)
const dialogImageUrl = ref('')//缩略图
const dialogVisible = ref(false)//是否显示缩略图
const filesUploadUrl = 'https://webman.wyx2013.cn/app/pan/index/upload' //上传地址 上传改为自己压缩后上传，这个没用了
const uploadRef = ref() //上传组件
const fileList = ref([])//上传图片列表
const headers = ref({ 'X-Requested-With': 'XMLHttpRequest', 'Authorization': authorization })
const selectedOptions = defineModel({ default: ()=>{
    return []
}})
//多选项
const selectedOptionsObj = computed(() => {
    const obj = {}
    selectedOptions.value.forEach(item => {
        obj[item] = true
    })
    return obj
})

//删除文件
const handleRemove = (file) => {
    if (file.response && file.response.data) {
        const hash = file.response.data.hash
        return http.get('app/pan/index/delete?hash=' + hash)
    }
}
//预览图片文件
const handlePictureCardPreview = function (url) {
    dialogImageUrl.value = url
    dialogVisible.value = true
}


//文件上传成功回调
const handleSucces = function (data, uploadFile = null, uploadFiles = null) {
    if (data && data.id) {
        ElNotification.success({ message: data.title + '上传成功,5秒后生成地缩略图', duration: 1000 })
        setTimeout(() => {
            uploadRef.value!.clearFiles()
            data.url = createThumbnail(data)
            addFile(data, data.pid)
        }, 5000)
    }
}

//自定义文件上传行为
const httpRequest = async function (UploadRequestOptions) {
    const formData = new FormData()
    formData.append('pid', props.dirId)
    const file = UploadRequestOptions.file
    const fileName = file.name
    if (/^image/i.test(file.type)) {
        const result = await compressImage(file)
        formData.append('file', result, result.name);
    } else {
        formData.append('file', UploadRequestOptions.file)
    }
    const p = new Promise((resolve, reject) => {
        const item = {
            formData,
            fileName,
            isUpload: false,
            progress: ref(0),
            onUploadProgress: function (e) {
                item.progress.value = Math.floor(e.progress * 100)
            },
            success: function (res) {
                handleSucces(res)
                resolve(res)
            }
        }
        fileQueueHandle.addFile(item)
    })
    return await p
}
</script>
<style scoped>
.square {
    width: 100%;
    position: relative;
}

.square:after {
    content: "";
    display: block;
    padding-bottom: 100%;
}

.content {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 1px dashed #b7b5b5;
    border-radius: 4%;
}

.file-checkbox {
    position: absolute;
    left: 10px;
    top: 10px;
    font-size: 2em;
    z-index: 2;
    line-height: 1em;
}
</style>